<template>
  <div class="app-container">
    <el-radio-group v-model="queryParams.deviceInventoryStatus" @change="tabCghange" style="margin-bottom: 30px;">
      <el-radio-button v-for="(item,index) in tabList" :key="index" :label="item.value">{{item.label || ''}}</el-radio-button>
    </el-radio-group>
    <el-form  :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="88px">
      <el-form-item label="厂家名称" prop="supplierId">
        <el-select
          v-model="queryParams.supplierId"
          placeholder="请选择厂家名称"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in supplierList"
            :key="dict.id"
            :label="dict.supplierName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属项目" prop="projectId" v-show="queryParams.deviceInventoryStatus">
        <el-select v-model="queryParams.projectId" filterable clearable placeholder="请选择所属项目">
          <el-option
            v-for="item1 in projectList"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="queryParams.deviceInventoryStatus === 0">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:faDevice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="queryParams.deviceInventoryStatus === 0">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleCaozuo('',{label:'出库',value:1})" :disabled="multiple"
          v-hasPermi="['system:faDevice:circulation']"
        >批量出库</el-button>
      </el-col>
      <el-col :span="1.5" v-if="queryParams.deviceInventoryStatus === 1">
        <el-button
          :type="item.type"
          plain  v-for="(item,index) in btnList" :key="index"
          size="mini"
          @click="handleCaozuo('',item)" :disabled="multiple"
          v-hasPermi="['system:faDevice:circulation']"
        >批量{{item.label}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="queryParams.deviceInventoryStatus === 0" type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
        v-hasPermi="['system:faDevice:importExcel']">导入</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :key="queryParams.deviceInventoryStatus" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" v-if="queryParams.deviceInventoryStatus != 2" />
      <el-table-column label="厂商名称" align="center" prop="supplierName" />
      <el-table-column label="设备类型" align="center" prop="devicetypeName" />
      <el-table-column label="设备ID" align="center" prop="deviceSn" show-overflow-tooltip />
      <el-table-column label="入库时间" v-if="queryParams.deviceInventoryStatus === 0" align="center" prop="createtimeFormat" />
      <el-table-column label="入库人员" v-if="queryParams.deviceInventoryStatus === 0" align="center" prop="creator" />
      <el-table-column label="出库时间" v-if="queryParams.deviceInventoryStatus === 1" align="center" prop="outStockTimeFormat" />
      <el-table-column label="出库人员" v-if="queryParams.deviceInventoryStatus === 1" align="center" prop="outStockOper" />
      <el-table-column label="所属项目" v-if="queryParams.deviceInventoryStatus === 1" align="center" prop="projectName" show-overflow-tooltip />
      <el-table-column label="状态" v-if="queryParams.deviceInventoryStatus === 2" align="center" prop="deviceInventoryStatus">
        <template slot-scope="{row}">
          <dict-tag :options="dict.type.device_status" :value="row.deviceInventoryStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" v-if="queryParams.deviceInventoryStatus === 1" align="center" prop="deviceInventoryStatus">
        <template slot-scope="{row}">
          <dict-tag :options="dict.type.device_status" :value="row.deviceInventoryStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" v-if="queryParams.deviceInventoryStatus === 1" align="center" prop="remark" />
      <el-table-column label="操作时间" v-if="queryParams.deviceInventoryStatus === 2" align="center" prop="createtimeFormat" />
      <el-table-column label="操作人员" v-if="queryParams.deviceInventoryStatus === 2" align="center" prop="creator" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{ row.deviceInventoryStatus == 6 || row.deviceInventoryStatus == 7 ? row.modifiedBy : row.creator}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" label-width="400" class-name="small-padding fixed-width" v-if="queryParams.deviceInventoryStatus !== 2" >
        <template slot-scope="{row}">
          <el-button
            size="mini"
            type="text" v-if="queryParams.deviceInventoryStatus === 0"
            @click="handleCaozuo(row,{label:'出库',value:1})"
            v-hasPermi="['system:faDevice:circulation']"
          >出库</el-button>
          <div class="flex_zhcenter" v-if="queryParams.deviceInventoryStatus === 1">
            <div v-for="(item,index) in btnList" :key="index">
              <el-button
              v-if="( item.value === 3 && row.devicetype != 13 ) ||
              ( item.value === 4 && row.devicetype != 13) || ( item.value === 5 )"
                size="mini" type="text"
                @click="handleCaozuo(row,item)"
                v-hasPermi="['system:faDevice:circulation']"
              >{{item.label}}</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <div v-if="form.deviceIds">
          <!-- <el-form-item label="操作ID" prop="deviceIdStr">
            <el-input v-model="form.deviceIdStr" disabled placeholder="请输入操作ID" />
          </el-form-item> -->
          <el-form-item label="选择设备ID" prop="shebeiId">
            <el-input v-model="form.shebeiId" disabled placeholder="请输入选择设备ID" />
          </el-form-item>
          <el-form-item :label="form.label + '至项目'" prop="parkProjectId"
          v-if="form.label == '出库'">
            <el-select v-model="form.parkProjectId" filterable :placeholder="'请选择' + form.label + '至项目'">
              <el-option
                v-for="item1 in projectList"
                :key="item1.id"
                :label="item1.name"
                :value="item1.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark" v-if="form.label == '维修' || form.label == '报废'">
            <el-input v-model="form.remark" type="textarea" :rows="6" placeholder="请输入供应商名称" />
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="厂家名称" prop="supplierId">
            <el-select
              v-model="form.supplierId"
              placeholder="请选择厂家名称"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in supplierList"
                :key="dict.id"
                :label="dict.supplierName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型" prop="devicetype">
            <el-select
              v-model="form.devicetype"
              placeholder="请选择设备类型"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in deviceLIst"
                :key="dict.enumValue"
                :label="dict.name"
                :value="dict.enumValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备ID" prop="deviceSn">
            <el-input v-model="form.deviceSn" placeholder="请输入设备ID" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="所属项目" prop="projectId">
          <el-select v-model="form.projectId" @change="xmChange" filterable clearable placeholder="请选择所属项目">
            <el-option
              v-for="item1 in projectList"
              :key="item1.id"
              :label="item1.name"
              :value="item1.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        name="excelfile"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入结果对话框 -->
    <el-dialog :title="uploadMsg.title" :visible.sync="uploadMsg.open" width="500px" append-to-body>
      <div class="diy-mb-3">{{ uploadMsg.msg }}</div>
      <div v-for="(item,index) in uploadMsg.error" :key="index">{{ item }}</div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, importExcel,getImportTemplate,circulation,recordCirculation,addFaDevice,updateFaDevice,} from "@/api/parking/equipInOut";
import { listAllFaParkProject,} from "@/api/config/projectPushManage";
import { getAllFaSupplier,} from "@/api/config/supplier";
import { selectFaDeviceType,} from "@/api/config/deviceType";
import {getToken} from "@/utils/auth";
export default {
  name: "OtherDevice",
  dicts: ['device_type_enum','device_status','device_communicat_mode',],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,supplierId:null,
        pageSize: 10,functionType:3,projectId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierId: [{ required: true, message: "厂家不能为空", trigger: "change" }],
        devicetype: [{ required: true, message: "设备类型不能为空", trigger: "change" }],
        deviceSn: [{ required: true, message: "设备ID不能为空", trigger: "blur" }],
        simNum: [{ required: true, message: "SIM卡号不能为空", trigger: "blur" }],
        svMode: [{ required: true, message: "通讯模式不能为空", trigger: "change" }],
        nbModel: [{ required: true, message: "NB模块型号不能为空", trigger: "blur" }],
        hwVer: [{ required: true, message: "硬件版本不能为空", trigger: "blur" }],
        deviceIds: [{ required: true, message: "设备不能为空", trigger: "blur" }],
        parkProjectId: [{ required: true, message: "项目不能为空", trigger: "change" }],
        remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
      },
      sbrkPermission:'system:faDevice:selectFaDevice7',//公司库存
      sbckPermission:'system:faDevice:selectFaDevice8',//项目设备
      sbjlPermission:'system:faDevice:selectFaDevice9',//设备记录
      tabList:[],
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/faDevice/importExcel"
      },
      //导入信息参数
      uploadMsg: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "导入结果",
        error: [],//错误信息
        msg: "", //提示信息
      },
      btnList:[//出库按钮
        {label:'回调',value:3,type:'primary',},
        {label:'报废',value:5,type:'danger',},
      ],
      projectList:[],//项目数据
      supplierList:[],//供应商列表
      deviceLIst:[],//设备列表
    };
  },
  created() {
    const user = this.$store.state.user
    const permissions = user.permissions
    const flag = !!permissions.find(item => item == this.sbrkPermission)
    const flag1 = !!permissions.find(item => item == this.sbckPermission)
    const flag2 = !!permissions.find(item => item == this.sbjlPermission)
    if (flag || permissions[0] == '*:*:*'){
      this.queryParams.deviceInventoryStatus = 0
      this.tabList.push({value: 0,label:'公司库存'})
    }else if(flag1 || permissions[0] == '*:*:*'){
      this.queryParams.deviceInventoryStatus = 1
    }else if(flag2 || permissions[0] == '*:*:*'){
      this.queryParams.deviceInventoryStatus = 2
    }
    if(flag1 || permissions[0] == '*:*:*') this.tabList.push({value: 1,label:'项目设备'})
    if(flag2 || permissions[0] == '*:*:*') this.tabList.push({value: 2,label:'设备记录'})
    this.listAllFaParkProject()
    this.selectFaDeviceType()
    this.getAllFaSupplier()
    this.getList();
  },
  methods: {
    xmChange(e){//项目改变
      let upload = {...this.upload}
      upload.url = process.env.VUE_APP_BASE_API + "/system/faDevice/importExcel" + (e ? `?projectId=${e}` : '')
      this.upload = {...upload}
    },
    async getAllFaSupplier(){//查询所有供应商列表
      let res = await getAllFaSupplier()
      let data = res.data || []
      this.supplierList = data
    },
    async selectFaDeviceType(){//查询设备列表
      let res = await selectFaDeviceType({functionType:3})
      let data = res.data || []
      this.deviceLIst = data
    },
    async listAllFaParkProject(){//查询返回所有项目列表
      let res = await listAllFaParkProject()
      let data = res.data || []
      this.projectList = data
    },
    async handleCaozuo(row,e){//按钮操作
      const ids = row ? [this.queryParams.deviceInventoryStatus === 2 ? row.recordId : row.id] : this.ids;
      let arr = []
      if(this.queryParams.deviceInventoryStatus === 2){
        arr = this.list.filter(item=>{
          return ids.some(i=>item.recordId == i)
        })
      }else{
        arr = this.list.filter(item=>{
          return ids.some(i=>item.id == i)
        })
      }
      arr = arr.map(item=>item.deviceSn)
      this.reset();
      this.open = true;
      this.title = (row ? '' : '批量') + e.label;
      this.form = {
        deviceInventoryType:e.value,
        deviceIds:ids,
        deviceIdStr:ids.toString(),
        shebeiId:arr.toString(),
        label:e.label,
        parkProjectId:row ? (row.parkProjectId || '') : '',
      }
      this.listAllFaParkProject()
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      let queryParams = {...this.queryParams}
      let dateRange = queryParams.dateRange || []
      if(dateRange.length) {
        queryParams.starttime = dateRange[0]
        queryParams.endtime = dateRange[1]
      }
      delete queryParams.dateRange
      getList(queryParams).then(response => {
          this.list = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {deviceInventoryStatus:this.queryParams.deviceInventoryStatus};
      this.resetForm("form");
      this.getAllFaSupplier()
      this.selectFaDeviceType()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    tabCghange(){
      this.multiple = true
      this.ids = []
      this.resetQuery()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if(this.queryParams.deviceInventoryStatus !== 2) this.ids = selection.map(item => item.id)
      if(this.queryParams.deviceInventoryStatus === 2) this.ids = selection.map(item => item.recordId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = {...row,deviceInventoryStatus:row.deviceInventoryStatus || 1};
      this.open = true;
      this.title = "修改项目推送管理";
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.deviceIds) {
            let obj = {}
            if(this.queryParams.deviceInventoryStatus === 2) {
              obj = {
                recordIds:this.form.deviceIds,
                deviceInventoryType:this.form.deviceInventoryType,
                remark:this.form.remark,
              }
            }else{
              obj = {
                deviceIds:this.form.deviceIds,
                parkProjectId:this.form.parkProjectId,
                deviceInventoryType:this.form.deviceInventoryType,
                remark:this.form.remark,
              }
            }
            if(this.queryParams.deviceInventoryStatus !== 0) delete obj.parkProjectId
            if(this.queryParams.deviceInventoryStatus === 2) {
              let arr = this.list.filter(item=>{
                return obj.recordIds.some(i=>item.recordId == i) && item.deviceInventoryStatus == 4
              })
              if(arr.length != obj.recordIds.length) return this.$modal.msgWarning("请选择维修的设备");
            }
            let api = this.queryParams.deviceInventoryStatus === 2 ? recordCirculation : circulation
            api(obj).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              if(this.form.deviceInventoryType == 1) {
                this.queryParams.deviceInventoryStatus = 1
              }else if(this.queryParams.deviceInventoryStatus == 1){
                this.queryParams.deviceInventoryStatus = 2
              }
              this.multiple = true
              this.ids = []
              this.getList();
            });
          }else{
            if (this.form.id != undefined) {
              updateFaDevice(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addFaDevice(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delInfo({id:dictIds});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.resetForm("form");
      let upload = {...this.upload}
      upload.url = process.env.VUE_APP_BASE_API + "/system/faDevice/importExcel"
      this.upload = {...upload}
      this.upload.title = "设备出入库数据导入";
      this.upload.open = true;
      this.listAllFaParkProject()
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/faDevice/getImportTemplate', {}, `设备出入库导入模版${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.code === 200) {
        this.uploadMsg.open = true;
        this.uploadMsg.error = response.data.error;
        this.uploadMsg.msg = response.data.msg
        this.getList();
      } else {
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
